package com.group2.view;

import java.awt.EventQueue;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.GroupLayout.Alignment;
import javax.swing.border.TitledBorder;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.table.DefaultTableModel;

import model.Book;

import java.awt.event.*;
import java.io.*;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Vector;

import model.*;
import static model.netBase.IP;

public class LibraryBookBorrowFrame extends JFrame {

	private JPanel contentPane;
	private JTextField BookNameSearch;
	private JTextField BookTypeSearch;
	private JTextField AuthorSearch;
	private JTable borrowtable;
	private static ArrayList<Book>list=null;
	private static String studentId;

	/**
	 * Launch the application.
	 */
//	public static void main(String[] args) {
//		EventQueue.invokeLater(new Runnable() {
//			public void run() {
//				try {
//					LibraryBookBorrowFrame frame = new LibraryBookBorrowFrame("1111");
//					frame.setVisible(true);
//				} catch (Exception e) {
//					e.printStackTrace();
//				}
//			}
//		});
//	}
	/**
	 * 拉取图书列表
	 */
		public void refresh() throws IOException, ClassNotFoundException {
			Socket socket = new Socket(IP(), 2000);//此处主机地址请自行修改
			//设置超时时间
			socket.setSoTimeout(3000);
			//构建IO
			OutputStream os = socket.getOutputStream();
			BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
			bw.write("21"+'\n');
			bw.flush();
			//从服务端输入到本地
			InputStream is = socket.getInputStream();
			ObjectInputStream in = new ObjectInputStream(is);
			Object obj = in.readObject();
			list = (ArrayList<Book>) obj;
			//输出输入流关闭
			is.close();
			os.close();
			socket.close();
		}
	/**
	 * Create the frame.
	 */
	public LibraryBookBorrowFrame(String id, Timer time) throws IOException, ClassNotFoundException {
		studentId=id;
		setTitle("图书借阅");
		//setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(380, 170, 680, 451);
		this.setLocationRelativeTo(null);
		this.setSize(781,440);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		this.setResizable(false);
		JPanel panel = new JPanel();
		panel.setBorder(new TitledBorder(null, "\u67E5\u8BE2\u6761\u4EF6", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		time.start();
		this.addMouseMotionListener(new MouseMotionListener() {@Override public void mouseDragged(MouseEvent e) {}@Override public void mouseMoved(MouseEvent e) {time.stop();}});
		this.addMouseListener(new MouseListener() {@Override public void mouseClicked(MouseEvent e) {}@Override public void mousePressed(MouseEvent e) {}@Override public void mouseReleased(MouseEvent e) {}@Override public void mouseEntered(MouseEvent e) {time.start();}@Override public void mouseExited(MouseEvent e) {time.start();}});
		JButton btnNewButton_2 = new JButton("借阅");
		btnNewButton_2.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					bookBorrowActionPerformed(e);
				} catch (IOException ex) {
					throw new RuntimeException(ex);
				} catch (ClassNotFoundException ex) {
					throw new RuntimeException(ex);
				} catch (Exception ex) {
					throw new RuntimeException(ex);
				}
			}
		});
		
		JScrollPane scrollPane = new JScrollPane();
		GroupLayout gl_contentPane = new GroupLayout(contentPane);
		gl_contentPane.setHorizontalGroup(gl_contentPane.createParallelGroup(Alignment.TRAILING).addGroup(gl_contentPane.createSequentialGroup().addGap(41).addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING).addComponent(panel, GroupLayout.DEFAULT_SIZE, 466, Short.MAX_VALUE).addComponent(scrollPane)).addGap(138)).addGroup(Alignment.LEADING, gl_contentPane.createSequentialGroup().addGap(285).addComponent(btnNewButton_2).addContainerGap(314, Short.MAX_VALUE)));
		gl_contentPane.setVerticalGroup(gl_contentPane.createParallelGroup(Alignment.LEADING).addGroup(gl_contentPane.createSequentialGroup().addGap(37).addComponent(panel, GroupLayout.PREFERRED_SIZE, 125, GroupLayout.PREFERRED_SIZE).addGap(18).addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 165, GroupLayout.PREFERRED_SIZE).addGap(18).addComponent(btnNewButton_2).addContainerGap(18, Short.MAX_VALUE)));
		
		borrowtable = new JTable();
		borrowtable.setModel(new DefaultTableModel(new Object[][] {},
			new String[]{
					"\u56FE\u4E66\u7F16\u53F7", "\u56FE\u4E66\u540D\u79F0", "\u56FE\u4E66\u7C7B\u578B", "\u4F5C\u8005", "\u51FA\u7248\u793E", "\u501F\u9605\u60C5\u51B5"}) {
			boolean[] canEdit = new boolean[]{false, false, false, false, false,false};
			public boolean isCellEditable(int rowIndex, int columnIndex) {
				return canEdit[columnIndex];
			}


		});
		scrollPane.setViewportView(borrowtable);
		
		JLabel lblNewLabel = new JLabel("图书名称：");
		
		BookNameSearch = new JTextField();
		BookNameSearch.setColumns(10);
		
		JLabel lblNewLabel_1 = new JLabel("图书类型：");
		
		BookTypeSearch = new JTextField();
		BookTypeSearch.setColumns(10);
		
		JLabel lblNewLabel_2 = new JLabel("作者：");
		
		AuthorSearch = new JTextField();
		AuthorSearch.setColumns(10);
		
		JButton btnNewButton = new JButton("查询");
		btnNewButton.setIcon(new ImageIcon(LibraryBookBorrowFrame.class.getResource("/images/search.png")));
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				try {
					booksearchActionPerformed(evt);
				} catch (IOException e) {
					throw new RuntimeException(e);
				} catch (ClassNotFoundException e) {
					throw new RuntimeException(e);
				}
			}
		});
		
		JButton btnNewButton_1 = new JButton("取消");
		btnNewButton_1.setIcon(new ImageIcon(LibraryBookBorrowFrame.class.getResource("/images/exit.png")));
		btnNewButton_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				try {
					resetValueActionPerformed(evt);
				} catch (IOException e) {
					throw new RuntimeException(e);
				} catch (ClassNotFoundException e) {
					throw new RuntimeException(e);
				}
			}
		});
		GroupLayout gl_panel = new GroupLayout(panel);
		gl_panel.setHorizontalGroup(gl_panel.createParallelGroup(Alignment.LEADING).addGroup(gl_panel.createSequentialGroup().addGroup(gl_panel.createParallelGroup(Alignment.LEADING, false).addGroup(gl_panel.createSequentialGroup().addGap(19).addComponent(lblNewLabel).addPreferredGap(ComponentPlacement.RELATED).addComponent(BookNameSearch, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).addGap(18).addComponent(lblNewLabel_1).addPreferredGap(ComponentPlacement.RELATED)).addGroup(Alignment.TRAILING, gl_panel.createSequentialGroup().addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addComponent(btnNewButton).addGap(33))).addGroup(gl_panel.createParallelGroup(Alignment.LEADING).addGroup(gl_panel.createSequentialGroup().addComponent(BookTypeSearch, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).addGap(18).addComponent(lblNewLabel_2).addPreferredGap(ComponentPlacement.RELATED).addComponent(AuthorSearch, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)).addGroup(gl_panel.createSequentialGroup().addGap(19).addComponent(btnNewButton_1))).addContainerGap(11, Short.MAX_VALUE)));
		gl_panel.setVerticalGroup(gl_panel.createParallelGroup(Alignment.LEADING).addGroup(gl_panel.createSequentialGroup().addGap(24).addGroup(gl_panel.createParallelGroup(Alignment.BASELINE).addComponent(lblNewLabel).addComponent(BookNameSearch, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).addComponent(lblNewLabel_1).addComponent(BookTypeSearch, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).addComponent(lblNewLabel_2).addComponent(AuthorSearch, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)).addGap(18).addGroup(gl_panel.createParallelGroup(Alignment.BASELINE).addComponent(btnNewButton).addComponent(btnNewButton_1)).addContainerGap(43, Short.MAX_VALUE)));
		panel.setLayout(gl_panel);
		contentPane.setLayout(gl_contentPane);
		refresh();
		this.fillbooktable(list);
	}
	/**
	 * 初始化表格数据
	 */
	private void fillbooktable(ArrayList<Book>course) {
		DefaultTableModel dtm=(DefaultTableModel) borrowtable.getModel();
		dtm.setRowCount(0);//设为0行
		//连接数据库
		try {
			int size = course.size();
			int index = 0;
			while (size > 0) {
				Vector v = new Vector();
				v.add(course.get(index).getBookId());v.add(course.get(index).getBookName()) ;v.add(course.get(index).getBookType());v.add(course.get(index).getBookAuthor());v.add(course.get(index).getBookPublisher());if(course.get(index).getBookAvailability().equals("0"))v.add("已借阅");
				dtm.addRow(v);
				size--;
				index++;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 图书查询事件处理
	 */
	private void booksearchActionPerformed(ActionEvent evt) throws IOException, ClassNotFoundException {
		String bookName=this.BookNameSearch.getText();
		String bookType=this.BookTypeSearch.getText();
		String bookAuthor=this.AuthorSearch.getText();
//		if(bookName.isEmpty()&&bookAuthor.isEmpty()&&bookType.isEmpty())
//		{
//			JOptionPane.showMessageDialog(null,"请输入查询条件");
//			return;
//		}
		Book book=new Book();
		book.setBookName(bookName);
		book.setBookType(bookType);
		book.setBookAuthor(bookAuthor);
		//连接数据库
		Socket socket = new Socket(IP(), 2000);//此处主机地址请自行修改
		//设置超时时间
		socket.setSoTimeout(3000);
		//构建IO
		OutputStream os = socket.getOutputStream();
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
		bw.write("22"+'\n'+""+'\n'+bookName+'\n'+bookType+'\n'+bookAuthor+'\n');
		bw.flush();
		//从服务端输入到本地
		InputStream is = socket.getInputStream();
		ObjectInputStream in = new ObjectInputStream(is);
		Object obj = in.readObject();
		list = (ArrayList<Book>) obj;
		//输出输入流关闭
		is.close();
		os.close();
		socket.close();
		fillbooktable(list);
	}

	/**
	 * 图书借阅事件处理
	 */
	private void bookBorrowActionPerformed(ActionEvent e) throws Exception {
		int row=-1;
		row=this.borrowtable.getSelectedRow();
		int bookID=(int)borrowtable.getValueAt(row, 0);
		String bookAvailability=(String)borrowtable.getValueAt(row, 5);
		Date d = new Date(System.currentTimeMillis());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
		String borrowTime = sdf.format(d);
		Book book=new Book();
		book.setBookId(bookID);
		book.setBookBorrowTime(borrowTime);
		if(row==-1)
		{
			JOptionPane.showMessageDialog(null,"请选择要借阅的图书");
			return;
		}
		if(bookAvailability=="已借阅")
		{
			JOptionPane.showMessageDialog(null,"您选择的图书已被借阅");
			return;
		}
		int n=JOptionPane.showConfirmDialog(null, "确定要借阅本书吗？");
		if(n==0) {
			//连接数据库
			//连接数据库
			Socket socket = new Socket(IP(), 2000);//此处主机地址请自行修改
			//设置超时时间
			socket.setSoTimeout(3000);
			//构建IO
			OutputStream os = socket.getOutputStream();
			InputStream is = socket.getInputStream();
			BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
			bw.write("24"+'\n'+studentId+'\n'+bookID+'\n'+borrowTime+'\n');
			bw.flush();
			//从服务端输入到本地
			BufferedReader br=new BufferedReader(new InputStreamReader(is));
			String str=br.readLine();
			//输出输入流关闭
			is.close();
			os.close();
			socket.close();
			if(str.equals("true")) {
				JOptionPane.showMessageDialog(null,"成功借阅，还书期限为："+book.addData(3,borrowTime));
				refresh();
				fillbooktable(list);
			}
			else JOptionPane.showMessageDialog(null,borrowtable.getValueAt(row, 1)+"借阅失败");
		}


	}
	/**
	 * 重置事件处理
	 */
	private void resetValueActionPerformed(ActionEvent evt) throws IOException, ClassNotFoundException {
		refresh();
		fillbooktable(list);
		this.resetValue();
	}
	/**
	 * 清空内容（重置）
	 */
	private void resetValue() {
		this.BookNameSearch.setText("");
		this.BookTypeSearch.setText("");
		this.AuthorSearch.setText("");
	}
}
